import { reactive, ref, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import { Notify } from 'vant'
import { useHomeStore } from '@/store/home'
import { usePersonStore } from '@/store/person'
import { IdLabel, IdName } from '@/types/global'
import { InsertPerson, Member } from '@/types/person'
import dayjs from 'dayjs'

export const useEntryEffect = () => {
  const router = useRouter()
  const homeStore = useHomeStore()
  const personStore = usePersonStore()
  const loading = ref(false)

  const communityList = homeStore.communityList
  const communityChildList = ref<IdLabel[]>([])

  const form = reactive<InsertPerson>({
    mch_id: '',
    community_id: '',
    // subcontractors_id: '',
    name: '',
    sex: '',
    phone: '',
    grid_name: '',
    grid_phone: '',
    principal_name: '',
    principal_phone: '',
    age: '',
    id_card: '',
    isolate_reason: '',
    address: '',
    dateRange: '',
    remark: '',
    person_category: '',
    personData: []
  })

  const query = reactive<InsertPerson>({
    isolate_starttime: '',
    isolate_endtime: '',
  })

  let personData = reactive<InsertPerson[]>([])

  const showCommunityPicker = ref(false) // 社区
  const onCommunityConfirm = (data: IdLabel) => {
    const { id, label } = data
    form.community_id = label
    query.community_id = id
    showCommunityPicker.value = false
    communityChildList.value = homeStore.communityALlChild[id] // 村/小区赋值
  }

  const showCommunityChildPicker = ref(false) // 小区
  const onCommunityChildConfirm = (data: IdLabel) => {
    const { id, label } = data
    form.mch_id = label
    query.mch_id = id
    showCommunityChildPicker.value = false
  }

  const showSubcontractorPicker = ref(false) // 分包单位
  const onSubcontractorConfirm = (data: IdName) => {
    const { id, name } = data
    form.subcontractors_id = name
    query.subcontractors_id = id
    showSubcontractorPicker.value = false
  }

  const sexList = personStore.sexList

  const curType = ref('') // 当前是主成员  还是其他成员
  const curIndex = ref(0) // 其他成员的index

  const showReasonPicker = ref(false) // 隔离原因
  const handleShowReasonPicker = (type:string, index?:number) => {
    showReasonPicker.value = true
    curType.value = type
    curIndex.value = index || 0
  }
  const onReasonConfirm = (data: IdName) => {
    const { id, name } = data

    if(curType.value === 'main'){
      // 主家庭成员
      form.isolate_reason = name
      query.isolate_reason = name
    } else {
      form.personData && (form.personData[curIndex.value]['isolate_reason'] = name)
      personData && (personData[curIndex.value]['isolate_reason'] = name)
    }
    
    showReasonPicker.value = false
  }

  const showCalendar = ref(false) // 隔离日期
  const handleShowCalendar = (type:string, index?:number) => {
    showCalendar.value = true
    curType.value = type
    curIndex.value = index || 0
  }
  const onCalendarConfirm = (values: any) => {
    const [start, end] = values
    showCalendar.value = false
    const isolate_starttime = `${dayjs(start).format('YYYY-MM-DD')}`
    const isolate_endtime = `${dayjs(end).format('YYYY-MM-DD')}`

    if(curType.value === 'main'){
      // 主家庭成员
      query.isolate_starttime = isolate_starttime
      query.isolate_endtime = isolate_endtime

      form.dateRange = `${isolate_starttime} 至 ${isolate_endtime}`
    } else {
      form.personData && (form.personData[curIndex.value]['dateRange'] = `${isolate_starttime} 至 ${isolate_endtime}`)
      personData && (personData[curIndex.value]['isolate_starttime'] = isolate_starttime)
      personData && (personData[curIndex.value]['isolate_endtime'] = isolate_endtime)
    }
  }

  const showCategoryPicker = ref(false) // 人员分类
  const handleShowCategoryPicker = (type:string, index?:number) => {
    showCategoryPicker.value = true
    curType.value = type
    curIndex.value = index || 0
  }
  const onCategoryConfirm = (data: IdName) => {
    const { id, name } = data
    if(curType.value === 'main'){
      // 主家庭成员
      form.person_category = name
      query.person_category = id
    } else {
      form.personData && (form.personData[curIndex.value]['person_category'] = name)
      personData && (personData[curIndex.value]['person_category'] = id)
    }
    showCategoryPicker.value = false
  }

  const handleAddMembers = () => {
    form.personData?.push({
      name: '',
      id_card: '',
      phone: '',
      isolate_reason: '',
      person_category: '',
      remark: '',
      dateRange: ''
    } as Member)
    personData.push({
      name: '',
      id_card: '',
      phone: '',
      isolate_reason: '',
      person_category: '',
      remark: '',
      isolate_starttime: '',
      isolate_endtime: '',
    } as Member)
  }

  const handleDeleteMembers = (index:number) => {
    form.personData?.splice(index, 1)
    personData.splice(index, 1)
  }

  const handleSubmit = async () => {
    if(personData.length === 0) {
      // 单个录入
      const params = { ...form, ...query }
      delete params.dateRange
      delete params.personData

      loading.value = true
      personStore
        .insertPerson(params)
        .then((code) => {
          loading.value = false
          if (code === 200) {
            Notify({
              type: 'success',
              message: '添加成功',
              duration: 2000,
              onOpened: () => {
                router.push({ path: '/person' })
              }
            })
          }
        })
        .catch(() => {
          loading.value = false
        })
    } else {
      // 获取公共数据并插入personData中
      // 其他家庭成员
      personData = personData.map((item, index) => {
        return {
          ...item,
          name: form.personData && form.personData[index].name || '',
          id_card: form.personData && form.personData[index].id_card || '',
          phone: form.personData && form.personData[index].phone || '',
          isolate_reason: form.personData && form.personData[index].isolate_reason || '',
          remark: form.personData && form.personData[index].remark || '',
          community_id: query.community_id,
          mch_id: query.mch_id,
          // subcontractors_id: query.subcontractors_id,
          grid_name: form.grid_name,
          grid_phone: form.grid_phone,
          principal_name: form.principal_name,
          principal_phone: form.principal_phone,
          address: form.address,
        }
      })
      // 主家庭成员
      personData.unshift({
        name: form.name,
        id_card: form.id_card,
        phone: form.phone,
        isolate_reason: form.isolate_reason,
        remark: form.remark,
        community_id: query.community_id,
        mch_id: query.mch_id,
        // subcontractors_id: query.subcontractors_id,
        person_category: query.person_category,
        grid_name: form.grid_name,
        grid_phone: form.grid_phone,
        address: form.address,
        isolate_starttime: query.isolate_starttime,
        isolate_endtime: query.isolate_endtime,
      })

      loading.value = true
      personStore
        .batchInsertPerson({personData})
        .then((code) => {
          loading.value = false
          if (code === 200) {
            Notify({
              type: 'success',
              message: '添加成功',
              duration: 2000,
              onOpened: () => {
                router.push({ path: '/person' })
              }
            })
          }
        })
        .catch(() => {
          loading.value = false
        })
    }
  }

  return {
    ...toRefs(form),
    loading,
    communityList,
    showCommunityPicker,
    onCommunityConfirm,
    communityChildList,
    showCommunityChildPicker,
    onCommunityChildConfirm,
    showSubcontractorPicker,
    onSubcontractorConfirm,
    sexList,
    showReasonPicker,
    onReasonConfirm,
    showCalendar,
    onCalendarConfirm,
    handleSubmit,
    showCategoryPicker,
    onCategoryConfirm,
    handleAddMembers,
    handleDeleteMembers,
    handleShowReasonPicker,
    handleShowCategoryPicker,
    handleShowCalendar
  }
}
